<template>
    <div>
        <el-tabs type="card" @tab-click="handleTabClick">
                <el-tab-pane :label="item.name" v-for="(item, index) in formtable" :key="index" >
                    <div style="padding:10px 20px;">    
                       <div v-if="item.istable">
                          <label v-for="(itemw, i) in item.subitem" :key="i" style="display:inline-block;margin:0 10px;">
                            <el-button type="text" :icon="itemw.icon" @click="getWlClick(itemw.value, index + 1, item)">{{ itemw.name }}</el-button>
                          </label>
                       </div>
                    </div>
                    <div v-if="item.value=='image'">
                        <el-upload
                            :http-request="uploadServerLog"
                            :show-file-list="false"
                            action="##"
                            class="upload-demo mr10 mb15"
                            multiple >
                            <div style="vertical-align: middle;margin-top:8px;">
                            <label v-if="imageUrl && imageUrl.length > 0" style="display:inline-block;height:50px;margin:10px;vertical-align:top;">
                                <img v-for="(item, index) in imageUrl" :key="index" :src="item.url" class="img" style="width:50px;" />
                            </label>
                            <label style="display:inline-block;border:3px dashed #999;border-radius: 8px;width:50px;height:50px;margin:10px;padding-top:4px;">
                                <i class="el-icon-plus avatar-uploader-icon" style="font-size:36px;font-weight:600;color:#999;"></i>
                            </label>
                            </div>
                        </el-upload>  
                    </div>
                    <div v-else>
                      <div v-loading="tableLoading">
                        <drawerTables :keyName="keyName" :tableName="item.value" :selectDialogIndex="selectDialogIndex" :disabledfiled="disabledfiled" :tableData="item.tableData" :tableInfo="item.tableHeader" :zidianData="item.datadictList" @selectTabel="selectTabel"></drawerTables>
                      </div>
                    </div>
                </el-tab-pane>
        </el-tabs>
        <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="70%" append-to-body top="5vh">
            <selectDialog v-if="dialogVisible" :total="diatotal" :tableInfo="selectInfo" :tableData="selectData" :searchField="searchField" :searchForm="searchForm" @handlerSearch="handlerSearch" @handlerSubmit="handlerSubmit"></selectDialog>
        </el-dialog>
        
    </div>
</template>
<script>
import { crudModuleListApi, crudModuleSaveDataApi, crudModuleInfoApi, crudsaleDetailApi,crudJoinListApi,
    crudModuleFindApi, configDictDataApi, crudFormInfoApi, crudModuleBatchDelApi, crudModuleDelApi, databaseInfoApi } from '@/api/develop'
import { getDictDatainfoApi, getDictDataListApi } from '@/api/form'
import { uploader } from '@/utils/uploadCloud'
import drawerTables from './table'
import selectDialog from './selectDialog.vue'
import { EventBus } from '@/libs/bus'
export default {
    name: 'HelloWorld',
    components: { drawerTables, selectDialog },
    data() {
        return {
            tableLoading: true,
            tabactive:'1',
            imageUrl: [],
            percentShow: false,
            dialogVisible: false,
            dialogImageUrl:'',
            tableInfo:[],
            gytableInfo:[],
            gytableData:[],
            getableData:[],
            getabelDataid:[],
            getableInfo:[],
            khtableData:[],
            khtableInfo:[],
            
            guigezidian: {
                types: "guige",
                level: 1,
                pid:'',
                name:'', 
            },
            tablebaseSearch:{
                is_field_all:'',
                is_system:1,
                limit: 100,
                order_by:{},
                page:1,
                scope_frame:'all',
                show_search_type:'0',
                view_search: [],
                view_search_boolean:'',
            },
            selectInfo: [],
            selectData: [],
            selectedData:[], // 选中数据
            dialogtitle:'',
            searchField:[ {
                field_name:'代码或名称',
                field_name_en:'name',
                form_value:'input',
                placeholder:'请输入代码或名称关键字'
            }],
            wuliaoxinxisearch: {
               page: 1,
               item_sn:'',
               item_desc:'',
               kekuanhao:'',
               kese:'',
            },
            searchForm: {
                name:''
            },
            selectDialogIndex: 1,
            childform: {
                wuliaodanganid: '' 
            },
            khselected:[],
            geselected:[],
            gyselected:[],
            selectedlist:[],
            optionStatus:[],// 状态选择
            formtable: [],
            formlength: 0,
            wuliaoleibieData: [], // 物料类别规格数据
            selectName:'',
            dictForm: {
                types: '',
                level: 1,
                pid:''
            },
            selectFiledData: {

            },
            diatotal: 0,
            tabIndexs: 0,
            disabledfiled:[],// 不可修改字符串
            allSearchForm: {
                page: 1,
                limit: 15,
                table: '',
                data: {},
            },
            formdatasBase: {
                joins: [ 
                    
                    {
                        type: "leftJoin",
                        table: "wuliaoxinxi",
                        alias: "x",
                        on: [
                            [
                                "m.wuliaodanganid",
                                "x.id"
                            ]
                        ]
                    }
                ],
                conditions: { // 主表查询条件
                    'm.shengchandanid': ''  
                },
                fields: [ // 关联表要显示的字段
                    "m.*",
                    "x.item_sn as wuliaobianma",
                    "x.item_depc as wuliaozhongwenmiaoshu",
                    "x.unit as unit"
                ],
                order: {
                    "m.id": "desc"
                }
            }
        }
    },
    props: {
        testFormData: {
            type: Object,
            default:()=>{
                return {}
            }
        },
        keyName: {
            type: String,
            default: ''
        },
        id: { // 档案id
           type: Number,
           default: 0
        },
        typeid: { // 档案类别id
            type: [Number, String],
            default: 0
        },
        isSubmit: {
            type: Number,
            default: 0
        },
        formDataAll: {
            type: Array,
            default: ()=>{
                return []
            }
        },
        pagestatus: { // 判断是否显示表单
            type: Number, 
            default: 1
        },
        flagStatu: {
            type: Number,
            default: 0,
        },
        treeData: {
            type: [Array, Object],
            default: ()=>{
                return []
            }
        },
        iscopy: { // 1复制0正常
            type: Number, 
            default: 0
        }
       
    },
    watch: {
        isSubmit(newValue) {
            if(newValue==1){
                console.log("tins", this.id)
                this.wuinit();
            }
        },
        
      
    },
    mounted(){
        this.wuinit();
    },
    methods:{
       
        async wuinit(){
            if(this.flagStatu != 2){
                // if(this.keyName=='wuliaoxinxi' || this.keyName == 'wuliaoleibieshuxing' || this.keyName=='wuliaoqingdanbiao'){
                //     this.formtable = this.formDataAll;
                //     await this.hadnlerInofinit();
                //     await this.handlerDict();
                //     this.$emit("handlerisSubmit")
                // }
                console.log("this.keyName", this.keyName)
                if(this.keyName == 'xiaoshoudingdan' ){ // 销售订单
                   this.disabledfiled = ['wuliaobianma', 'wuliaozhongwenmiaoshu', 'danwei', 'changkuanhao', 'kekuanhao', 'kese', 'kechima', 'pinpai', 'jine']
                }else if(this.keyName == 'shengchandan'){
                    this.disabledfiled = ['wuliaobianma', 'wuliaozhongwenmiaoshu', 'danwei', 'fangdanmiaoshu', 'jishu', 'tiaoji', 'weipishu', 'weifashu', 'wanchengshu', 'xucaigouqi', 'bumendaima','bumenmingcheng', ]
                }
                this.formtable = this.formDataAll;
                this.selectName = this.formtable[0].value;

                await this.hadnlerInofinit();
                this.$emit("handlerisSubmit")
            }
        },
   
        // tab切换
        async handleTabClick(event){
            let i = event.index;
            this.selectDialogIndex = Number(i) + 1;
            this.tableData = this.formtable[i].tableData;
        },
        // 获取表格数据及字典数据
        async hadnlerInofinit(){
            console.log("this.formtable",this.id, this.formtable)
            let i= 0;
            for(let i=0;i<this.formtable.length;i++){
                if(this.formtable[i].istable){
                    this.formtable[i].tableData = []
                    this.formtable[i].deleteData = []
                    if(this.formtable[i].value){
                        let resdatas = await crudModuleInfoApi(this.formtable[i].value, 0);
                        await this.handlerallFiledData(resdatas, i)
                        if(this.id){ 
                            if(this.keyName=='wuliaoleibieshuxing'){ // 物料类别属性
                                this.formtable[i].search.wuliaoleibiebianmaid = this.id;
                            }else if(this.keyName=='wuliaoqingdanbiao'){ // 物料清单搜索
                                this.formtable[i].search.fuwuliaobianmaid = this.id;
                            }else if(this.keyName=='wuliaoxinxi'){ // 物料档案
                                this.formtable[i].search.wuliaodanganid = this.id;
                            }else if(this.keyName=='xiaoshoudingdan'){
                                this.formtable[i].search.xiaoshoudingdanid = this.id;
                            }else if(this.keyName == 'shengchandan'){
                                this.formtable[i].search.shengchandanid = this.id;
                            }
                            if(this.formtable[i].value == 'shengchandanwuliao'){
                                this.allSearchForm.table = this.formtable[i].value +' as ' + 'm',
                                this.formdatasBase.conditions['m.shengchandanid'] = this.id;
                                this.allSearchForm.data = encodeURI(JSON.stringify(this.formdatasBase))
                                let allformdata = this.allSearchForm;
                                let data = await crudJoinListApi(allformdata)
                                await this.handlerTableAllData(data, i, 1);
                            }else{
                                let search1 = this.formtable[i].search;
                                let search2 = this.tablebaseSearch;
                                let search3 = {...search1, ...search2}
                                let data = await crudModuleListApi(this.formtable[i].value, search3);
                                await this.handlerTableAllData(data, i);
                            }
                            
                        }
                    }
                }
            }
           
        },

        // 获取表头数据
        async handlerallFiledData(resdata, index){
            let showFieldData = resdata.data.showField;
            let searchFieldData = resdata.data.seniorSearch;
            let searchdefault = this.formtable[index].search;
            let objs = {},searchobj = {},dataictnamearr=[]
            let fileallData = [];
            for(let i=0;i < showFieldData.length;i++){
                objs[showFieldData[i].field_name_en] = ''
                objs.disabled = false;
                if(searchFieldData.length > 0){
                    if(searchFieldData[i]){
                       searchobj[searchFieldData[i].field_name_en] = ''
                    }
                }
                if(showFieldData[i].field_name_en != 'fuwuliaobianmaid' && showFieldData[i].field_name_en != 'xiaoshoudingdanid'){
                    if(showFieldData[i].field_name_en == 'bumenid'){
                        showFieldData[i].field_name = '部门名称/代码'
                    }
                    fileallData.push(showFieldData[i]); // 在索引1的位置
                }
            }
            this.formtable[index].form = objs;
            this.formtable[index].search = {...searchdefault, ...searchobj};
            let fielddatanew = []
            if(this.formtable[index].value == 'xiaoshoumingxi'){
                for(let i=0;i<fileallData.length;i++){
                    if(fileallData[i].field_name_en != 'zhizaodanhao' || fileallData[i].field_name_en !== 'pingshenzhuangtai' || fileallData[i].field_name_en !== 'pihe'){
                        fielddatanew.push(fileallData[i])
                    }
                }
                console.log("fileallDataA", fielddatanew)
                this.formtable[index].tableHeader = fielddatanew;
            }else{
                console.log("fileallData", fileallData)
               this.formtable[index].tableHeader = fileallData;
            }
            if(index == 0 ){
                this.tableLoading = false;
            }
            await this.handlerDict(fileallData, index)
        },
         // 表格展示数据
        async handlerTableAllData(data, index, status=0){
            if(data.status==200){
                let resdataList = data.data.list;
                console.log("resdataList", resdataList)
                for(let i=0;i < resdataList.length;i++){
                    if(status==1){ // 生产物料单
                        if(resdataList[i].zhuangtai){
                            resdataList[i].zhuangtai = this.handlerReplace(resdataList[i].zhuangtai)
                        }
                        if(resdataList[i].laiyuan){
                            resdataList[i].laiyuan = this.handlerReplace(resdataList[i].laiyuan)
                        }
                        if(resdataList[i].bibie){ // 币别
                            resdataList[i].bibie = this.handlerReplace(resdataList[i].laiyuan)
                        }
                        if(resdataList[i].danwei){ // 单位
                            resdataList[i].danwei = this.handlerReplace(resdataList[i].danwei)
                        }else{
                            if(resdataList[i].unit){
                              resdataList[i].danwei = this.handlerReplace(resdataList[i].unit)
                            }else{
                                resdataList[i].danwei = ''
                            }
                        }
                        if(resdataList[i].bumenid == '0'){
                            resdataList[i].bumenid = ''
                        }
                    }else{
                        if(resdataList[i].zhuangtai && resdataList[i].zhuangtai.length > 0){ // 状态
                            resdataList[i].zhuangtai = (resdataList[i].zhuangtai).join(',')
                        }
                        if(resdataList[i].bibie && resdataList[i].bibie.length > 0){ // 币别
                            resdataList[i].bibie = (resdataList[i].bibie).join(',')
                        }
                        if(resdataList[i].laiyuan && resdataList[i].laiyuan.length > 0){ // 状态
                            resdataList[i].laiyuan = (resdataList[i].laiyuan).join(',')
                        }
                        if(this.formtable[index].value=='xiaoshoumingxi'){
                            
                        }else{
                            if(resdataList[i].wuliaodanganid){
                                let wlbmobj = { id: this.id, name: resdataList[i].wuliaodanganid || '' }
                                resdataList[i].wuliaodanganid = wlbmobj
                            }
                        }
                        if(resdataList[i].wuliaoleibiebianmaid){
                            let wlbmobj = { id: this.id, name: resdataList[i].wuliaoleibiebianmaid || '' }
                            resdataList[i].wuliaoleibiebianmaid = wlbmobj
                        }
                        if(resdataList[i].xiaoshoudingdanid){
                            let wlbmobj = { id: this.id, name: resdataList[i].xiaoshoudingdanid || '' }
                            resdataList[i].xiaoshoudingdanid = wlbmobj
                        }
                        if(resdataList[i].bumenid == '0'){
                            resdataList[i].bumenid = ''
                        }
                    }
                }
                this.formtable[index].tableData = resdataList;
                this.formtable[index].oldData = JSON.parse(JSON.stringify(resdataList));
            }

        },
        // 获取字典和实体表下拉选择框数据

        async handlerDict(headerData, index){
          let itemdata = headerData;
          let obj = {}
          if(itemdata && itemdata.length > 0){
          for(let i=0;i<itemdata.length;i++){
             if(itemdata[i].data_dict_id){ // 字典查询下拉选择框数据
                obj[itemdata[i].field_name_en] = []
                let dataictnamearr = [], datadictDta = null;
                if(itemdata[i].data_dict_id == 64){ // 单位
                    dataictnamearr.push("danwei");
                    this.dictForm.types = dataictnamearr;
                    datadictDta = await getDictDataListApi(this.dictForm)
                }else if(itemdata[i].data_dict_id == 63){ // 物料来源
                    dataictnamearr.push("wuliaolaiyua");
                    this.dictForm.types = dataictnamearr;
                    datadictDta = await getDictDataListApi(this.dictForm)
                }else if(itemdata[i].data_dict_id == 67){ // 状态
                    dataictnamearr.push("zhuangtai");
                    this.dictForm.types = dataictnamearr;
                    datadictDta = await getDictDataListApi(this.dictForm)
                }else{
                    let datadict = await getDictDatainfoApi(itemdata[i].data_dict_id)
                    dataictnamearr.push(datadict.data.ident);
                    this.dictForm.types = dataictnamearr;
                    datadictDta = await getDictDataListApi(this.dictForm)
                }
                obj[itemdata[i].field_name_en] = datadictDta.data.list;
                // this.formtable[index].datadictList = datadictDta.data.list
             }else if(itemdata[i].association_crud_id){ // 关联表选择查询
                if(itemdata[i].association_crud_id==55){ // 工序设置实体表
                    let datalist = await crudModuleListApi('gongxushezhong', {page: 1, limit: 100, gongxushezhifuxuan: [['1']]});
                    obj[itemdata[i].field_name_en] = datalist.data.list;               
                    
                }else{ // 其他实体表
                let database = await databaseInfoApi(itemdata[i].association_crud_id)
                let tabbasename = database.data.table_name_en;
                let datalist = await crudModuleListApi(tabbasename, {page: 1, limit: 100});
                obj[itemdata[i].field_name_en] = datalist.data.list;
                }
                // this.formtable[index].datadictList = datadictDta.data.list
             }
          }
          this.formtable[index].datadictList = obj;
        }
      },
        
        
        // 选中表格数据返回
        selectTabel(val, index=0){
            if(index==0){
                if(val && val.length > 0){
                  this.formtable[this.selectDialogIndex-1].selectData = val   
                }
            }else{ // 拖拽排序
                let vals = val;
                let tabledatadra = this.formtable[this.selectDialogIndex-1].tableData;
                tabledatadra.splice(vals.new, 0, vals.row)
                this.formtable[this.selectDialogIndex-1].tableData = tabledatadra;
                this.$set(this.formtable, this.formtable)
            }
        },
        // 搜索 返回
        handlerSearch(data){
            if(this.selectName == 'guige'){ // 字段
                this.guigezidian.name = data.name;
                this.getGuigezidian(this.guigezidian, this.selectDialogIndex);
            }else if(this.selectName == 'wuliaoxinxi'){
                this.wuliaoxinxisearch.item_sn = data.item_sn || '';

                this.handlerWuliaoSelect();
            }else{ // 实体表
                let searchForm = {...this.tablebaseSearch, ...data};
                this.getshiTiTableBase(this.selectName,searchForm, this.selectDialogIndex, this.selectFiledData, 2);
            }
        },
        // 提交数据返回
        handlerSubmit(index=0, data){
            console.log("handlerSubmitA：", index, data, this.selectName)
            if(index==0){ // 取消关闭弹窗
                this.dialogVisible = false;
            }else{
                if(this.selectName == 'guige'){ // 物料档案规格表
                    if(data.length > 0){
                        for(let i=0;i<data.length;i++){
                            let formobj  = {}
                            formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                            formobj.guigedaima = data[i].value;
                            formobj.guigeleixing = data[i].name;
                            formobj.zhuangtai = '正常'; //{name:'正常', color:'#303030'};
                            formobj.id = '';
                            this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                        }
                    }  
                }else if(this.selectName=='wuliaoxinxi'){ // 销售明细选择物料信息表数据返回
                    if(data.length > 0){
                       let selectdata = this.handlerSubmitwuliaoxinxiData(data);
                       this.formtable[this.selectDialogIndex-1].tableData = JSON.parse(JSON.stringify(selectdata));
                    }
                }else{
                    if(data.length > 0){
                        if(this.formtable[this.selectDialogIndex-1].value == 'xiaoshoumingxi'){ 
                            for(let i=0;i<data.length;i++){
                                let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                formobj.wuliaodanganid = data[i].id;
                                formobj.wuliaobianma = data[i].item_sn;
                                formobj.wuliaozhongwenmiaoshu = data[i].item_depc
                                formobj.changkunhao = data[i].model;
                                formobj.danwei = data[i].unit;
                                formobj.xuhao = data[i].xuhao ? Number(data[i].xuhao) + 1 : 1;
                            }
                            console.log("formobj", formobj)
                            this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                        }else{
                            for(let i=0;i<data.length;i++){
                                const keys = Object.keys(this.formtable[this.selectDialogIndex-1].form)
                                if(keys && keys.length > 0){
                                    let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                    for(let key of keys){
                                        if(data[i][key]){
                                            if(key in data[i]){
                                                formobj[key] = data[i][key] || '';
                                            }
                                        }
                                    }
                                    // if(formobj.kehao){ // 档案客户信息表批量添加要获取客户信息的id才能把客号添加成功
                                    //     formobj.kehaoid = data[i].id;
                                    // }
                                    this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                                }else{
                                    this.formtable[this.selectDialogIndex-1].tableData.push(data[i]);
                                }
                            }
                        }
                    }  
                }
                if(index==2){ // 确认退出关闭弹窗
                    this.dialogVisible = false;
                }
            }
            
        },

        // 添加，选择，删除等方法
        async getWlClick(val, indexstatus=0, item){
            this.selectDialogIndex = indexstatus;
            this.dialogtitle = item.name;
            if(val=='add'){ // 添加
                this.selectName = item.subitem[0].tablename;
                if(this.selectName=='guige'){ // 选择规格(规格字典表)
                    this.searchForm  = { name: ''}
                   this.searchField = [ {field_name_en: 'name', field_name:'代码或名称'}]; 
                   this.getGuigezidian(this.guigezidian, indexstatus);
                }else{ // 实体表
                    if(this.selectName){ // 根据从其他表添加数据
                        if(this.selectName=='wuliaoxinxi'){
                            this.searchField = [ {field_name_en:'item_sn', field_name:'物料编码'},
                                    {field_name_en:'item_depc', field_name:'物料描述'},
                                    {field_name_en:'kekuanhao', field_name:'客款号'},
                                    {field_name_en:'kese', field_name:'客色'}]
                            this.selectInfo = [{ field_name: "物料编码",field_name_en: "item_sn",form_value: "input" },
                                { field_name: "物料描述",field_name_en: "item_depc", form_value: "input"},
                                { field_name: "厂款号",field_name_en: "model", form_value: "input"},
                                { field_name: "客款号 ",field_name_en: "kekuanhao", form_value: "input"},
                                { field_name: "客色",field_name_en: "kese",form_value: "input"},
                                { field_name: "客码",field_name_en: "kechima", form_value: "input"},
                                { field_name: "品牌",field_name_en: "pinpai", form_value: "input"},
                                { field_name: "单位", field_name_en: "unit", form_value: "input"},
                                { field_name: "备注",field_name_en: "remark",form_value: "input",}
                            ],
                            this.handlerWuliaoSelect();
                        }else{
                            let resdatas = await crudModuleInfoApi(this.selectName, item.subitem[0].id || 0);
                            if(resdatas.status==200){
                                this.selectFiledData = resdatas.data;
                                let search1 = this.formtable[indexstatus-1].search
                                let search2 = this.tablebaseSearch;
                                let search3 = {...search1, ...search2};
                                this.getshiTiTableBase(this.selectName, search3, indexstatus, resdatas.data);
                            }
                        }
                    }else{ // 直接添加数据
                        let dataheader = this.formtable[indexstatus-1].tableHeader;
                        console.log("dataheader", dataheader)
                        let obj = {}
                        for(let i = 0; i < dataheader.length;i++){
                            obj[dataheader[i].field_name_en] = ''
                        }
                        this.formtable[indexstatus-1].tableData.push(obj)
                    }
                }
            }else if(val=='select'){ // 选择
               this.selectName = this.keyName;
            //    let wldadatas = crudModuleListApi(this.keyName);
               this.dialogtitle = '从其他物料档案选择规格'
               this.dialogVisible = true;
               this.selectInfo = this.formtable[0].tableHeader;
            }else if(val=='delete'){ // 删除
                let newdata = [],newselectd=this.formtable[indexstatus-1].deleteData;
                let dataArray = this.formtable[indexstatus-1].tableData;
                let selectids = this.formtable[indexstatus-1].selectData;
                if(selectids.length > 0){
                        for(let i=0; i< dataArray.length;i++){
                            if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                                newdata.push(dataArray[i]);
                            }else{
                                if(dataArray[i].id){
                                    newselectd.push(dataArray[i].id);
                                }
                            }
                        }
                        this.formtable[indexstatus-1].tableData = newdata;
                        if(newselectd.length > 0){
                            this.formtable[indexstatus-1].deleteData = newselectd;
                        }
                    // this.$modalSure('您确定要删除这条数据,删除后将无法恢复，请确认哦').then(() => {
                    //     for(let i=0; i< dataArray.length;i++){
                    //         if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                    //             newdata.push(dataArray[i]);
                    //         }else{
                    //             if(dataArray[i].id){
                    //                 newselectd.push(dataArray[i].id);
                    //             }
                    //         }
                    //     }
                    //     if(newselectd.length > 0){
                    //        this.handlerDeleteData(this.formtable[indexstatus-1].value, {ids: newselectd}, newdata, indexstatus);
                    //     }
                    // })
                }else{
                    this.$message.error("请选择要删除的数据")
                }
            }else if(val=='guige'){ // 列出物料规格
                let lbid = 0
                if(this.typeid && this.typeid.includes('-')){
                    lbid = this.typeid.split('-')[0]
                }else{
                    lbid = this.typeid;
                }
                if(lbid){
                   this.getwuliaoleibieList(indexstatus, "leibieguigebiao", {wuliaoleibiebianmaid: lbid})
                }else{
                    this.$message.error("请先选择物料类别")
                }
            }
        },
        // 物料档案关联客户管理供应商查询
        handlerWuliaoSelect() {
            crudsaleDetailApi(this.wuliaoxinxisearch).then(res=>{
            }).catch(res=>{
                if(res.data.status==200){
                    this.dialogVisible = true;
                    let selectList = res.data.data.list;
                    for(let i=0;i< selectList.length;i++){
                        selectList[i].unit = this.handlerUnitFilter(selectList[i].unit);
                    }
                    this.diatotal = res.data.data.count;
                    this.selectData = selectList;

                }  
            })
        },
        handlerUnitFilter(unit){
            if(!unit) return ''
            let unitval = unit.replace(/\//g, '');
            let danweiData = this.formtable[this.selectDialogIndex-1].datadictList.danwei || [];
            for(let i=0;i,danweiData.length;i++){
                if(unitval == danweiData[i].value) 
                  return danweiData[i].name
            }
            return ''
        },
        handlerSubmitwuliaoxinxiData(data) {
            let resultdata = this.formtable[this.selectDialogIndex-1].tableData || [];
            let xuhao = 0;
            if(resultdata.length > 0){
                xuhao = resultdata[resultdata.length - 1].xuhao || resultdata.length + 1;
            }
            for(let i=0;i<data.length;i++){
                let obj = {
                    xuhao: xuhao > 0 ? xuhao + 1 : 1 + i,
                    wuliaodanganid : data[i].danAnId,
                    wuliaobianma : data[i].item_sn,
                    wuliaozhongwenmiaoshu : data[i].item_depc,
                    danwei : data[i].unit || '',
                    changkuanhao : data[i].model || '',
                    kekuanhao : data[i].kekuanhao || '',
                    kese : data[i].kese || '',
                    kechima : data[i].kechima || '',
                    pinpai : data[i].pinpai || '',
                    xiaoshoudingdanid : '',
                    kepo : '',
                    kepoxuhao : '',
                    shuliang : '',
                    mianfeishu : '',
                    choudanshu : '',
                    choudanbeizhu : '',
                    danjia : data[i].danjia || '',
                    jine : '',
                    keqi : '',
                    yewuchangqi : '',
                    paikuanriqi : '',
                    qiliaoriqi : '',
                    beizhu : data[i].remark,
                    zhuangtai : this.handlerZhuangtai(data[i].state_code), // 3正常 2完成 1取消
                    id: '',
                }
                resultdata.push(obj)
            }

            return resultdata;
        },
        handlerZhuangtai(val){
            if(!val) return '3'
            let zhuangtai = val.replace(/\//g, '')
            return zhuangtai;

        },



        // 关联物料档案实体表删除接口
        handlerDeleteData(keyName, data, newdata, indexstatus){
                crudModuleBatchDelApi(keyName, data).then((res) => {
                    if(res.status==200){
                        this.formtable[indexstatus-1].tableData = newdata;
                        // this.formtable[indexstatus-1].deleteData = newselectd;
                        if(this.keyName == 'wuliaoqingdanbiao'){
                           EventBus.$emit('event-tree-grandchild', this.formtable[indexstatus-1].tableData)
                        }
                    }
                })
            
           
        },
        
        // 获取物料类别规格列表数据
        async getwuliaoleibieList(indexstatus, keyName, data={}) {
            crudModuleListApi(keyName, data).then((res) => {
                if(res.status==200){
                    let array1 = this.formtable[indexstatus-1].tableData;
                    let array2 = res.data.list;
                    let arr3 = []
                    for(let i=0;i<array2.length;i++){
                        delete array2[i].wuliaoleibiebianmaid;
                        delete array2[i].is_share;
                        delete array2[i].id;
                        array2[i].guigeneirong_two=''
                        if(array2[i].wuliaodanganid){
                            array2[i].wuliaodanganid = ''
                        }else{
                            array2[i].wuliaodanganid = ''
                        }
                        arr3.push(array2[i])
                    }
                    const mergedArray = [...array1, ...arr3];
                    const result = mergedArray.filter(
                      (item, index, self) => index === self.findIndex(t => t.guigedaima === item.guigedaima)
                    );
                    this.formtable[indexstatus-1].tableData = result;
                }
            })
        },
       
        // 获取实体表单信息
        getTableFormInput(id, keyName) {
            crudFormInfoApi(id).then((res) => {
                let optiondata = res.data.options;
                if(keyName =='guige'){
                    for(let i=0;i<optiondata.length;i++){
                        if(optiondata[i].name=='状态'){
                            this.optionStatus = optiondata[i].options.optionItems;
                            break;
                        }
                    }
                }
            })
        },
        // 获取规格编码字典数据(添加弹窗显示)
        getGuigezidian(data, indexstatus=0){
            // 调用configDictDataApi函数，传入keyName和0作为参数
            configDictDataApi(data).then((res) => {
                 let resdata = res.data.list;
                 this.diatotal = res.data.count;
                 this.selectInfo = [
                    {
                        field_name: "代码",
                        field_name_en: "value",
                        form_value: "input",
                    },
                    {
                        field_name: "名称",
                        field_name_en: "name",
                        form_value: "input",
                    }
                 ]
                 this.selectData = []
                 let selectedlist = []
                 this.formtable[indexstatus-1].tableData.map((item)=>{
                    selectedlist.push(item.guigedaima)
                 })
                 if(selectedlist.length > 0){
                 for(let i=0;i< resdata.length;i++){
                     if(!selectedlist.includes(resdata[i].value)){
                        this.selectData.push(resdata[i])
                     }
                 }
                }else{
                    this.selectData = resdata
                }
                this.dialogVisible = true;
            })
        },
        // 获取实体表数据(添加弹窗显示)
        async getshiTiTableBase(keyName, formdata, indexstatus=0, fieldData='', searchstatus=1){
            crudModuleListApi(keyName, formdata).then((res) => {
                if(res.status==200){
                    let resdata = res.data.list;
                    this.diatotal = res.data.count;
                    let headerData = fieldData.showField;
                    let headerInfo = headerData.slice(0,2)
                    this.selectInfo = headerInfo
                    if(searchstatus==1){
                        let searchForms = {}
                        if(fieldData.seniorSearch.length > 0){
                            this.searchField = fieldData.seniorSearch;
                            for(let i=0;i < fieldData.seniorSearch.length;i++){
                                searchForms[fieldData.seniorSearch[i].field_name_en] = ''
                            }
                        }else{
                            this.searchField = headerInfo;
                            for(let i=0;i < headerInfo.length;i++){
                                searchForms[headerInfo[i].field_name_en] = ''
                            }
                        }
                        this.searchForm = searchForms
                    }
                    this.selectData = []
                    let selectedlist = []
                    this.formtable[indexstatus-1].tableData.map((item)=>{
                        selectedlist.push(item[headerInfo[0].field_name_en])
                    })
                    if(selectedlist.length > 0){
                        if(resdata.length > 0){
                            for(let i=0;i< resdata.length;i++){
                                if(!selectedlist.includes(resdata[i][headerInfo[0].field_name_en])){
                                    this.selectData.push(resdata[i])
                                }
                            }
                        }else{
                            this.selectData = []
                        }
                    }else{
                        this.selectData = resdata
                    }
                    this.dialogVisible = true;     
                }
            })
        },
        // 上传文件方法
        uploadServerLog(params) {
            this.percentShow = true
            const file = params.file
            let options = {
                way: 2,
                relation_type: '',
                relation_id: '',
                eid: ''
            }
            uploader(file, 0, options)
            .then((res) => {
                // 获取上传文件渲染页面
                if (res.data.name) {
                   this.imageUrl.push(res.data)
                }
            })
            .catch((err) => {})
        },    
        handlerReplace(val){
            if(val.includes("/")){
                let newStr = val.replace(/\//g, "");
                return newStr;
            }else{
                return val;
            }
        }     
    }
 }

</script>
<style>


</style>